package com.sql.handler.util;

import java.sql.Connection;
import java.sql.SQLException;
import java.util.HashMap;
import java.util.Map;
import java.util.Timer;
import java.util.TimerTask;


public class CacheConnectionArray{
	
	private final static int DELAY = 60 * 1000;
	private Map<String, Timer> timers = new HashMap<>();
	private Map<String, Connection> connections = new HashMap<>();

	public void add(final Connection conn){
		if(conn == null){
			return;
		}
		String key = conn.toString();
		final Timer t = new Timer();
		t.schedule(new TimerTask() {
			@Override
			public void run() {
				try {
					conn.close();
					t.cancel();
				} catch (SQLException e) {
					e.printStackTrace();
				}
			}
		}, DELAY);
		timers.put(key, t);
		connections.put(key, conn);
	}

	public synchronized void remove(Connection conn){
		if(conn == null){
			return;
		}
		String key = conn.toString();
		if(timers.get(key) != null){
			timers.remove(key).cancel();
		}
		connections.remove(key);
	}

}
